#!/bin/bash

# 检查是否传入了参数
if [ -z "$1" ]; then
    echo "Usage: $0 <server|gostc|proxy> [additional arguments...]"
    exit 1
fi

# 获取脚本参数
TYPE=$1
shift  # 移除第一个参数，剩下的参数作为额外参数

# 目标目录和安装配置
case "$TYPE" in
    "server")
        TARGET_DIR="/usr/local/gostc-admin"
        BINARY_NAME="server"
        INSTALL_COMMAND="service install"
        ;;
    "gostc")
        TARGET_DIR="/usr/local/bin"
        BINARY_NAME="gostc"
        INSTALL_COMMAND=""
        ;;
    "proxy")
        TARGET_DIR="/usr/local/gostc-proxy"
        BINARY_NAME="gostc-proxy"
        INSTALL_COMMAND=""
        ;;
    *)
        echo "Invalid type. Use 'server', 'gostc' or 'proxy'."
        exit 1
        ;;
esac

# 创建目标目录（如果不存在）
sudo mkdir -p "$TARGET_DIR"

# 获取当前系统的操作系统类型和架构
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)

# 根据架构和系统确定文件后缀
FILE_SUFFIX=""
case "$ARCH" in
    "x86_64")
        if [ "$OS" = "linux" ]; then
            # 检查CPU特性以确定v1/v3
            if grep -q "avx512" /proc/cpuinfo; then
                FILE_SUFFIX="amd64_v3"
            elif grep -q "avx2" /proc/cpuinfo; then
                FILE_SUFFIX="amd64_v1"
            else
                FILE_SUFFIX="amd64_v1"
            fi
        else
            FILE_SUFFIX="amd64_v1"
        fi
        ;;
    "i686"|"i386")
        FILE_SUFFIX="386_sse2"
        ;;
    "aarch64"|"arm64")
        FILE_SUFFIX="arm64_v8.0"
        ;;
    "armv7l")
        # 检查ARM版本
        ARM_ARCH=$(uname -m | grep -oE '[0-9]+$')
        if [ -n "$ARM_ARCH" ]; then
            if [ "$ARM_ARCH" -ge 7 ]; then
                FILE_SUFFIX="arm_7"
            elif [ "$ARM_ARCH" -ge 6 ]; then
                FILE_SUFFIX="arm_6"
            else
                FILE_SUFFIX="arm_5"
            fi
        else
            FILE_SUFFIX="arm_7"
        fi
        ;;
    "armv6l")
        FILE_SUFFIX="arm_6"
        ;;
    "armv5l")
        FILE_SUFFIX="arm_5"
        ;;
    "mips64")
        # 检查是否是little-endian
        if lscpu | grep -qi "little endian"; then
            FILE_SUFFIX="mips64le_hardfloat"
        else
            FILE_SUFFIX="mips64_hardfloat"
        fi
        ;;
    "mips")
        # 检查是否是little-endian
        if lscpu | grep -qi "little endian"; then
            # 检查是否支持硬件浮点
            if lscpu | grep -qi "FPU"; then
                FILE_SUFFIX="mipsle_hardfloat"
            else
                FILE_SUFFIX="mipsle_softfloat"
            fi
        else
            if lscpu | grep -qi "FPU"; then
                FILE_SUFFIX="mips_hardfloat"
            else
                FILE_SUFFIX="mips_softfloat"
            fi
        fi
        ;;
    "riscv64")
        FILE_SUFFIX="riscv64_rva20u64"
        ;;
    "s390x")
        FILE_SUFFIX="s390x"
        ;;
    *)
        echo "Unsupported architecture: $ARCH"
        exit 1
        ;;
esac

# 如果是Windows系统
if [[ "$OS" == *"mingw"* || "$OS" == *"cygwin"* ]]; then
    OS="windows"
fi

# 构建文件名和下载URL
BASE_URL="https://alist.sian.one/direct/gostc/gostc-open"
FILE_NAME="${TYPE}_${OS}_${FILE_SUFFIX}"
if [ "$OS" = "windows" ]; then
    FILE_NAME="${FILE_NAME}.zip"
else
    FILE_NAME="${FILE_NAME}.tar.gz"
fi
DOWNLOAD_URL="${BASE_URL}/${FILE_NAME}"

echo "Downloading $FILE_NAME..."
curl -L -o "$FILE_NAME" "$DOWNLOAD_URL"

if [ $? -ne 0 ]; then
    echo "Failed to download $FILE_NAME"
    exit 1
fi

# 解压文件到目标目录
echo "Extracting $FILE_NAME to $TARGET_DIR..."
if [[ "$FILE_NAME" == *.zip ]]; then
    sudo unzip -o "$FILE_NAME" -d "$TARGET_DIR"
elif [[ "$FILE_NAME" == *.tar.gz ]]; then
    sudo tar -xzf "$FILE_NAME" -C "$TARGET_DIR"
else
    echo "Unsupported file format: $FILE_NAME"
    exit 1
fi

# 设置文件权限
if [ -f "$TARGET_DIR/$BINARY_NAME" ]; then
    sudo chown root:root "$TARGET_DIR/$BINARY_NAME"
    sudo chmod +x "$TARGET_DIR/$BINARY_NAME"
    echo "Set permissions for $TARGET_DIR/$BINARY_NAME"
else
    echo "Binary file $BINARY_NAME not found in $TARGET_DIR."
    exit 1
fi

# 如果是server，运行安装命令
if [ "$TYPE" = "server" ]; then
    echo "Running installation command for server..."
    sudo "$TARGET_DIR/$BINARY_NAME" $INSTALL_COMMAND "$@"
fi

# 清理下载的文件
rm -f "$FILE_NAME"
echo "Installation complete. Files are in $TARGET_DIR."